
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Making queries &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="Aggregation" href="aggregation.html" />
    <link rel="prev" title="Models" href="models.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="models.html" title="Models">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="aggregation.html" title="Aggregation">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-queries">
            
  <div class="section" id="s-making-queries">
<span id="making-queries"></span><h1>Making queries<a class="headerlink" href="#making-queries" title="永久链接至标题">¶</a></h1>
<p>Once you've created your <a class="reference internal" href="models.html"><span class="doc">data models</span></a>, Django
automatically gives you a database-abstraction API that lets you create,
retrieve, update and delete objects. This document explains how to use this
API. Refer to the <a class="reference internal" href="../../ref/models/index.html"><span class="doc">data model reference</span></a> for full
details of all the various model lookup options.</p>
<p>Throughout this guide (and in the reference), we'll refer to the following
models, which comprise a Weblog application:</p>
<div class="highlight-python notranslate" id="queryset-model-example"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Blog</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">tagline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Author</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">email</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">EmailField</span><span class="p">()</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>

<span class="k">class</span> <span class="nc">Entry</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">blog</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Blog</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">headline</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">255</span><span class="p">)</span>
    <span class="n">body_text</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>
    <span class="n">pub_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">mod_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>
    <span class="n">authors</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ManyToManyField</span><span class="p">(</span><span class="n">Author</span><span class="p">)</span>
    <span class="n">number_of_comments</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>
    <span class="n">number_of_pingbacks</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>
    <span class="n">rating</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">()</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">headline</span>
</pre></div>
</div>
<div class="section" id="s-creating-objects">
<span id="creating-objects"></span><h2>Creating objects<a class="headerlink" href="#creating-objects" title="永久链接至标题">¶</a></h2>
<p>To represent database-table data in Python objects, Django uses an intuitive
system: A model class represents a database table, and an instance of that
class represents a particular record in the database table.</p>
<p>To create an object, instantiate it using keyword arguments to the model class,
then call <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> to save it to the database.</p>
<p>Assuming models live in a file <code class="docutils literal notranslate"><span class="pre">mysite/blog/models.py</span></code>, here's an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">blog.models</span> <span class="kn">import</span> <span class="n">Blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Beatles Blog&#39;</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s1">&#39;All the latest Beatles news.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>This performs an <code class="docutils literal notranslate"><span class="pre">INSERT</span></code> SQL statement behind the scenes. Django doesn't hit
the database until you explicitly call <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>.</p>
<p>The <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> method has no return value.</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p><a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> takes a number of advanced options not
described here. See the documentation for
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> for complete details.</p>
<p class="last">To create and save an object in a single step, use the
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.create" title="django.db.models.query.QuerySet.create"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create()</span></code></a> method.</p>
</div>
</div>
<div class="section" id="s-saving-changes-to-objects">
<span id="saving-changes-to-objects"></span><h2>Saving changes to objects<a class="headerlink" href="#saving-changes-to-objects" title="永久链接至标题">¶</a></h2>
<p>To save changes to an object that's already in the database, use
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>.</p>
<p>Given a <code class="docutils literal notranslate"><span class="pre">Blog</span></code> instance <code class="docutils literal notranslate"><span class="pre">b5</span></code> that has already been saved to the database,
this example changes its name and updates its record in the database:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b5</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;New name&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b5</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>This performs an <code class="docutils literal notranslate"><span class="pre">UPDATE</span></code> SQL statement behind the scenes. Django doesn't hit
the database until you explicitly call <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>.</p>
<div class="section" id="s-saving-foreignkey-and-manytomanyfield-fields">
<span id="saving-foreignkey-and-manytomanyfield-fields"></span><h3>Saving <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> and <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> fields<a class="headerlink" href="#saving-foreignkey-and-manytomanyfield-fields" title="永久链接至标题">¶</a></h3>
<p>Updating a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> field works exactly the same
way as saving a normal field -- assign an object of the right type to the field
in question. This example updates the <code class="docutils literal notranslate"><span class="pre">blog</span></code> attribute of an <code class="docutils literal notranslate"><span class="pre">Entry</span></code>
instance <code class="docutils literal notranslate"><span class="pre">entry</span></code>, assuming appropriate instances of <code class="docutils literal notranslate"><span class="pre">Entry</span></code> and <code class="docutils literal notranslate"><span class="pre">Blog</span></code>
are already saved to the database (so we can retrieve them below):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">blog.models</span> <span class="kn">import</span> <span class="n">Blog</span><span class="p">,</span> <span class="n">Entry</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cheese_blog</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;Cheddar Talk&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span><span class="o">.</span><span class="n">blog</span> <span class="o">=</span> <span class="n">cheese_blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>Updating a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> works a little
differently -- use the
<a class="reference internal" href="../../ref/models/relations.html#django.db.models.fields.related.RelatedManager.add" title="django.db.models.fields.related.RelatedManager.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> method on the field
to add a record to the relation. This example adds the <code class="docutils literal notranslate"><span class="pre">Author</span></code> instance
<code class="docutils literal notranslate"><span class="pre">joe</span></code> to the <code class="docutils literal notranslate"><span class="pre">entry</span></code> object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">blog.models</span> <span class="kn">import</span> <span class="n">Author</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">joe</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;Joe&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">joe</span><span class="p">)</span>
</pre></div>
</div>
<p>To add multiple records to a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> in one
go, include multiple arguments in the call to
<a class="reference internal" href="../../ref/models/relations.html#django.db.models.fields.related.RelatedManager.add" title="django.db.models.fields.related.RelatedManager.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a>, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">john</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;John&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paul</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;Paul&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">george</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;George&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ringo</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s2">&quot;Ringo&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">john</span><span class="p">,</span> <span class="n">paul</span><span class="p">,</span> <span class="n">george</span><span class="p">,</span> <span class="n">ringo</span><span class="p">)</span>
</pre></div>
</div>
<p>Django will complain if you try to assign or add an object of the wrong type.</p>
</div>
</div>
<div class="section" id="s-retrieving-objects">
<span id="s-id1"></span><span id="retrieving-objects"></span><span id="id1"></span><h2>Retrieving objects<a class="headerlink" href="#retrieving-objects" title="永久链接至标题">¶</a></h2>
<p>To retrieve objects from your database, construct a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> via a
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> on your model class.</p>
<p>A <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> represents a collection of objects
from your database. It can have zero, one or many <em>filters</em>. Filters narrow
down the query results based on the given parameters. In SQL terms, a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> equates to a <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> statement,
and a filter is a limiting clause such as <code class="docutils literal notranslate"><span class="pre">WHERE</span></code> or <code class="docutils literal notranslate"><span class="pre">LIMIT</span></code>.</p>
<p>You get a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> by using your model's
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a>. Each model has at least one
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a>, and it's called
<a class="reference internal" href="../../ref/models/class.html#django.db.models.Model.objects" title="django.db.models.Model.objects"><code class="xref py py-attr docutils literal notranslate"><span class="pre">objects</span></code></a> by default. Access it directly via the
model class, like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span>
<span class="go">&lt;django.db.models.manager.Manager object at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Foo&#39;</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s1">&#39;Bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">objects</span>
<span class="go">Traceback:</span>
<span class="go">    ...</span>
<span class="go">AttributeError: &quot;Manager isn&#39;t accessible via Blog instances.&quot;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">Managers</span></code> are accessible only via model classes, rather than from model
instances, to enforce a separation between &quot;table-level&quot; operations and
&quot;record-level&quot; operations.</p>
</div>
<p>The <a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> is the main source of <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code> for
a model. For example, <code class="docutils literal notranslate"><span class="pre">Blog.objects.all()</span></code> returns a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> that contains all <code class="docutils literal notranslate"><span class="pre">Blog</span></code> objects in
the database.</p>
<div class="section" id="s-retrieving-all-objects">
<span id="retrieving-all-objects"></span><h3>Retrieving all objects<a class="headerlink" href="#retrieving-all-objects" title="永久链接至标题">¶</a></h3>
<p>The simplest way to retrieve objects from a table is to get all of them. To do
this, use the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.all" title="django.db.models.query.QuerySet.all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">all()</span></code></a> method on a
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">all_entries</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.all" title="django.db.models.query.QuerySet.all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">all()</span></code></a> method returns a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> of all the objects in the database.</p>
</div>
<div class="section" id="s-retrieving-specific-objects-with-filters">
<span id="retrieving-specific-objects-with-filters"></span><h3>Retrieving specific objects with filters<a class="headerlink" href="#retrieving-specific-objects-with-filters" title="永久链接至标题">¶</a></h3>
<p>The <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> returned by
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.all" title="django.db.models.query.QuerySet.all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">all()</span></code></a> describes all objects in the
database table. Usually, though, you'll need to select only a subset of the
complete set of objects.</p>
<p>To create such a subset, you refine the initial
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>, adding filter conditions. The two
most common ways to refine a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> are:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">filter(**kwargs)</span></code></dt>
<dd>Returns a new <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> containing objects
that match the given lookup parameters.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">exclude(**kwargs)</span></code></dt>
<dd>Returns a new <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> containing objects
that do <em>not</em> match the given lookup parameters.</dd>
</dl>
<p>The lookup parameters (<code class="docutils literal notranslate"><span class="pre">**kwargs</span></code> in the above function definitions) should
be in the format described in <a class="reference internal" href="#field-lookups">Field lookups</a> below.</p>
<p>For example, to get a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> of blog entries
from the year 2006, use <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> like
so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2006</span><span class="p">)</span>
</pre></div>
</div>
<p>With the default manager class, it is the same as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2006</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="s-chaining-filters">
<span id="s-id2"></span><span id="chaining-filters"></span><span id="id2"></span><h4>Chaining filters<a class="headerlink" href="#chaining-filters" title="永久链接至标题">¶</a></h4>
<p>The result of refining a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> is itself a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>, so it's possible to chain
refinements together. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">headline__startswith</span><span class="o">=</span><span class="s1">&#39;What&#39;</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">pub_date__gte</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
<span class="gp">... </span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">pub_date__gte</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">30</span><span class="p">)</span>
<span class="gp">... </span><span class="p">)</span>
</pre></div>
</div>
<p>This takes the initial <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> of all entries
in the database, adds a filter, then an exclusion, then another filter. The
final result is a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> containing all
entries with a headline that starts with &quot;What&quot;, that were published between
January 30, 2005, and the current day.</p>
</div>
<div class="section" id="s-filtered-querysets-are-unique">
<span id="s-id3"></span><span id="filtered-querysets-are-unique"></span><span id="id3"></span><h4>Filtered <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are unique<a class="headerlink" href="#filtered-querysets-are-unique" title="永久链接至标题">¶</a></h4>
<p>Each time you refine a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>, you get a
brand-new <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> that is in no way bound to
the previous <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>. Each refinement creates
a separate and distinct <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> that can be
stored, used and reused.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q1</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__startswith</span><span class="o">=</span><span class="s2">&quot;What&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q2</span> <span class="o">=</span> <span class="n">q1</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">pub_date__gte</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q3</span> <span class="o">=</span> <span class="n">q1</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__gte</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">())</span>
</pre></div>
</div>
<p>These three <code class="docutils literal notranslate"><span class="pre">QuerySets</span></code> are separate. The first is a base
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> containing all entries that contain a
headline starting with &quot;What&quot;. The second is a subset of the first, with an
additional criteria that excludes records whose <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> is today or in the
future. The third is a subset of the first, with an additional criteria that
selects only the records whose <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> is today or in the future. The
initial <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> (<code class="docutils literal notranslate"><span class="pre">q1</span></code>) is unaffected by the
refinement process.</p>
</div>
<div class="section" id="s-querysets-are-lazy">
<span id="s-id4"></span><span id="querysets-are-lazy"></span><span id="id4"></span><h4><code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are lazy<a class="headerlink" href="#querysets-are-lazy" title="永久链接至标题">¶</a></h4>
<p><code class="docutils literal notranslate"><span class="pre">QuerySets</span></code> are lazy -- the act of creating a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> doesn't involve any database
activity. You can stack filters together all day long, and Django won't
actually run the query until the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> is
<em>evaluated</em>. Take a look at this example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__startswith</span><span class="o">=</span><span class="s2">&quot;What&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__lte</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">q</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">body_text__icontains</span><span class="o">=</span><span class="s2">&quot;food&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">q</span><span class="p">)</span>
</pre></div>
</div>
<p>Though this looks like three database hits, in fact it hits the database only
once, at the last line (<code class="docutils literal notranslate"><span class="pre">print(q)</span></code>). In general, the results of a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> aren't fetched from the database
until you &quot;ask&quot; for them. When you do, the
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> is <em>evaluated</em> by accessing the
database. For more details on exactly when evaluation takes place, see
<a class="reference internal" href="../../ref/models/querysets.html#when-querysets-are-evaluated"><span class="std std-ref">什么时候 QuerySet 被执行</span></a>.</p>
</div>
</div>
<div class="section" id="s-retrieving-a-single-object-with-get">
<span id="s-retrieving-single-object-with-get"></span><span id="retrieving-a-single-object-with-get"></span><span id="retrieving-single-object-with-get"></span><h3>Retrieving a single object with <code class="docutils literal notranslate"><span class="pre">get()</span></code><a class="headerlink" href="#retrieving-a-single-object-with-get" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> will always give you a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>, even if only a single object matches
the query - in this case, it will be a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> containing a single element.</p>
<p>If you know there is only one object that matches your query, you can use the
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> method on a
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> which returns the object directly:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">one_entry</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>You can use any query expression with
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>, just like with
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> - again, see <a class="reference internal" href="#field-lookups">Field lookups</a>
below.</p>
<p>Note that there is a difference between using
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>, and using
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> with a slice of <code class="docutils literal notranslate"><span class="pre">[0]</span></code>. If
there are no results that match the query,
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> will raise a <code class="docutils literal notranslate"><span class="pre">DoesNotExist</span></code>
exception. This exception is an attribute of the model class that the query is
being performed on - so in the code above, if there is no <code class="docutils literal notranslate"><span class="pre">Entry</span></code> object with
a primary key of 1, Django will raise <code class="docutils literal notranslate"><span class="pre">Entry.DoesNotExist</span></code>.</p>
<p>Similarly, Django will complain if more than one item matches the
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> query. In this case, it will raise
<a class="reference internal" href="../../ref/exceptions.html#django.core.exceptions.MultipleObjectsReturned" title="django.core.exceptions.MultipleObjectsReturned"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MultipleObjectsReturned</span></code></a>, which again is an
attribute of the model class itself.</p>
</div>
<div class="section" id="s-other-queryset-methods">
<span id="other-queryset-methods"></span><h3>Other <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> methods<a class="headerlink" href="#other-queryset-methods" title="永久链接至标题">¶</a></h3>
<p>Most of the time you'll use <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.all" title="django.db.models.query.QuerySet.all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">all()</span></code></a>,
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>,
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> and
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a> when you need to look up
objects from the database. However, that's far from all there is; see the
<a class="reference internal" href="../../ref/models/querysets.html#queryset-api"><span class="std std-ref">QuerySet API Reference</span></a> for a complete list of all the
various <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> methods.</p>
</div>
<div class="section" id="s-limiting-querysets">
<span id="s-id5"></span><span id="limiting-querysets"></span><span id="id5"></span><h3>Limiting <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s<a class="headerlink" href="#limiting-querysets" title="永久链接至标题">¶</a></h3>
<p>Use a subset of Python's array-slicing syntax to limit your
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> to a certain number of results. This
is the equivalent of SQL's <code class="docutils literal notranslate"><span class="pre">LIMIT</span></code> and <code class="docutils literal notranslate"><span class="pre">OFFSET</span></code> clauses.</p>
<p>For example, this returns the first 5 objects (<code class="docutils literal notranslate"><span class="pre">LIMIT</span> <span class="pre">5</span></code>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[:</span><span class="mi">5</span><span class="p">]</span>
</pre></div>
</div>
<p>This returns the sixth through tenth objects (<code class="docutils literal notranslate"><span class="pre">OFFSET</span> <span class="pre">5</span> <span class="pre">LIMIT</span> <span class="pre">5</span></code>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[</span><span class="mi">5</span><span class="p">:</span><span class="mi">10</span><span class="p">]</span>
</pre></div>
</div>
<p>Negative indexing (i.e. <code class="docutils literal notranslate"><span class="pre">Entry.objects.all()[-1]</span></code>) is not supported.</p>
<p>Generally, slicing a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> returns a new
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> -- it doesn't evaluate the query. An
exception is if you use the &quot;step&quot; parameter of Python slice syntax. For
example, this would actually execute the query in order to return a list of
every <em>second</em> object of the first 10:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[:</span><span class="mi">10</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span>
</pre></div>
</div>
<p>Further filtering or ordering of a sliced queryset is prohibited due to the
ambiguous nature of how that might work.</p>
<p>To retrieve a <em>single</em> object rather than a list
(e.g. <code class="docutils literal notranslate"><span class="pre">SELECT</span> <span class="pre">foo</span> <span class="pre">FROM</span> <span class="pre">bar</span> <span class="pre">LIMIT</span> <span class="pre">1</span></code>), use an index instead of a slice. For
example, this returns the first <code class="docutils literal notranslate"><span class="pre">Entry</span></code> in the database, after ordering
entries alphabetically by headline:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;headline&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
<p>This is roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;headline&#39;</span><span class="p">)[</span><span class="mi">0</span><span class="p">:</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
</pre></div>
</div>
<p>Note, however, that the first of these will raise <code class="docutils literal notranslate"><span class="pre">IndexError</span></code> while the
second will raise <code class="docutils literal notranslate"><span class="pre">DoesNotExist</span></code> if no objects match the given criteria. See
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> for more details.</p>
</div>
<div class="section" id="s-field-lookups">
<span id="s-field-lookups-intro"></span><span id="field-lookups"></span><span id="field-lookups-intro"></span><h3>Field lookups<a class="headerlink" href="#field-lookups" title="永久链接至标题">¶</a></h3>
<p>Field lookups are how you specify the meat of an SQL <code class="docutils literal notranslate"><span class="pre">WHERE</span></code> clause. They're
specified as keyword arguments to the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>
methods <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a>,
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a> and
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>.</p>
<p>Basic lookups keyword arguments take the form <code class="docutils literal notranslate"><span class="pre">field__lookuptype=value</span></code>.
(That's a double-underscore). For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__lte</span><span class="o">=</span><span class="s1">&#39;2006-01-01&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>translates (roughly) into the following SQL:</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">blog_entry</span> <span class="k">WHERE</span> <span class="n">pub_date</span> <span class="o">&lt;=</span> <span class="s1">&#39;2006-01-01&#39;</span><span class="p">;</span>
</pre></div>
</div>
<div class="admonition-how-this-is-possible admonition">
<p class="first admonition-title">How this is possible</p>
<p class="last">Python has the ability to define functions that accept arbitrary name-value
arguments whose names and values are evaluated at runtime. For more
information, see <a class="reference external" href="https://docs.python.org/3/tutorial/controlflow.html#tut-keywordargs" title="(在 Python v3.9)"><span>Keyword Arguments</span></a> in the official Python tutorial.</p>
</div>
<p>The field specified in a lookup has to be the name of a model field. There's
one exception though, in case of a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> you
can specify the field name suffixed with <code class="docutils literal notranslate"><span class="pre">_id</span></code>. In this case, the value
parameter is expected to contain the raw value of the foreign model's primary
key. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog_id</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>If you pass an invalid keyword argument, a lookup function will raise
<code class="docutils literal notranslate"><span class="pre">TypeError</span></code>.</p>
<p>The database API supports about two dozen lookup types; a complete reference
can be found in the <a class="reference internal" href="../../ref/models/querysets.html#field-lookups"><span class="std std-ref">field lookup reference</span></a>. To give you
a taste of what's available, here's some of the more common lookups you'll
probably use:</p>
<dl class="docutils">
<dt><a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-exact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">exact</span></code></a></dt>
<dd><p class="first">An &quot;exact&quot; match. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__exact</span><span class="o">=</span><span class="s2">&quot;Cat bites dog&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Would generate SQL along these lines:</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="p">...</span> <span class="k">WHERE</span> <span class="n">headline</span> <span class="o">=</span> <span class="s1">&#39;Cat bites dog&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>If you don't provide a lookup type -- that is, if your keyword argument
doesn't contain a double underscore -- the lookup type is assumed to be
<code class="docutils literal notranslate"><span class="pre">exact</span></code>.</p>
<p>For example, the following two statements are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>  <span class="c1"># Explicit form</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>         <span class="c1"># __exact is implied</span>
</pre></div>
</div>
<p class="last">This is for convenience, because <code class="docutils literal notranslate"><span class="pre">exact</span></code> lookups are the common case.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-iexact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iexact</span></code></a></dt>
<dd><p class="first">A case-insensitive match. So, the query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">name__iexact</span><span class="o">=</span><span class="s2">&quot;beatles blog&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p class="last">Would match a <code class="docutils literal notranslate"><span class="pre">Blog</span></code> titled <code class="docutils literal notranslate"><span class="pre">&quot;Beatles</span> <span class="pre">Blog&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;beatles</span> <span class="pre">blog&quot;</span></code>, or
even <code class="docutils literal notranslate"><span class="pre">&quot;BeAtlES</span> <span class="pre">blOG&quot;</span></code>.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-contains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">contains</span></code></a></dt>
<dd><p class="first">Case-sensitive containment test. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Roughly translates to this SQL:</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="p">...</span> <span class="k">WHERE</span> <span class="n">headline</span> <span class="k">LIKE</span> <span class="s1">&#39;%Lennon%&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>Note this will match the headline <code class="docutils literal notranslate"><span class="pre">'Today</span> <span class="pre">Lennon</span> <span class="pre">honored'</span></code> but not
<code class="docutils literal notranslate"><span class="pre">'today</span> <span class="pre">lennon</span> <span class="pre">honored'</span></code>.</p>
<p class="last">There's also a case-insensitive version, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-icontains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">icontains</span></code></a>.</p>
</dd>
<dt><a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-startswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">startswith</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-endswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">endswith</span></code></a></dt>
<dd>Starts-with and ends-with search, respectively. There are also
case-insensitive versions called <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-istartswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">istartswith</span></code></a> and
<a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-iendswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iendswith</span></code></a>.</dd>
</dl>
<p>Again, this only scratches the surface. A complete reference can be found in the
<a class="reference internal" href="../../ref/models/querysets.html#field-lookups"><span class="std std-ref">field lookup reference</span></a>.</p>
</div>
<div class="section" id="s-lookups-that-span-relationships">
<span id="s-id6"></span><span id="lookups-that-span-relationships"></span><span id="id6"></span><h3>Lookups that span relationships<a class="headerlink" href="#lookups-that-span-relationships" title="永久链接至标题">¶</a></h3>
<p>Django offers a powerful and intuitive way to &quot;follow&quot; relationships in
lookups, taking care of the SQL <code class="docutils literal notranslate"><span class="pre">JOIN</span></code>s for you automatically, behind the
scenes. To span a relationship, use the field name of related fields
across models, separated by double underscores, until you get to the field you
want.</p>
<p>This example retrieves all <code class="docutils literal notranslate"><span class="pre">Entry</span></code> objects with a <code class="docutils literal notranslate"><span class="pre">Blog</span></code> whose <code class="docutils literal notranslate"><span class="pre">name</span></code>
is <code class="docutils literal notranslate"><span class="pre">'Beatles</span> <span class="pre">Blog'</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__name</span><span class="o">=</span><span class="s1">&#39;Beatles Blog&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This spanning can be as deep as you'd like.</p>
<p>It works backwards, too. While it <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_query_name" title="django.db.models.ForeignKey.related_query_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">can</span> <span class="pre">be</span> <span class="pre">customized</span></code></a>, by default you refer to a &quot;reverse&quot;
relationship in a lookup using the lowercase name of the model.</p>
<p>This example retrieves all <code class="docutils literal notranslate"><span class="pre">Blog</span></code> objects which have at least one <code class="docutils literal notranslate"><span class="pre">Entry</span></code>
whose <code class="docutils literal notranslate"><span class="pre">headline</span></code> contains <code class="docutils literal notranslate"><span class="pre">'Lennon'</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you are filtering across multiple relationships and one of the intermediate
models doesn't have a value that meets the filter condition, Django will treat
it as if there is an empty (all values are <code class="docutils literal notranslate"><span class="pre">NULL</span></code>), but valid, object there.
All this means is that no error will be raised. For example, in this filter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__authors__name</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>(if there was a related <code class="docutils literal notranslate"><span class="pre">Author</span></code> model), if there was no <code class="docutils literal notranslate"><span class="pre">author</span></code>
associated with an entry, it would be treated as if there was also no <code class="docutils literal notranslate"><span class="pre">name</span></code>
attached, rather than raising an error because of the missing <code class="docutils literal notranslate"><span class="pre">author</span></code>.
Usually this is exactly what you want to have happen. The only case where it
might be confusing is if you are using <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-isnull"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">isnull</span></code></a>. Thus:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__authors__name__isnull</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>will return <code class="docutils literal notranslate"><span class="pre">Blog</span></code> objects that have an empty <code class="docutils literal notranslate"><span class="pre">name</span></code> on the <code class="docutils literal notranslate"><span class="pre">author</span></code> and
also those which have an empty <code class="docutils literal notranslate"><span class="pre">author</span></code> on the <code class="docutils literal notranslate"><span class="pre">entry</span></code>. If you don't want
those latter objects, you could write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__authors__isnull</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">entry__authors__name__isnull</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="s-spanning-multi-valued-relationships">
<span id="spanning-multi-valued-relationships"></span><h4>Spanning multi-valued relationships<a class="headerlink" href="#spanning-multi-valued-relationships" title="永久链接至标题">¶</a></h4>
<p>When you are filtering an object based on a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> or a reverse
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>, there are two different sorts of filter
you may be interested in. Consider the <code class="docutils literal notranslate"><span class="pre">Blog</span></code>/<code class="docutils literal notranslate"><span class="pre">Entry</span></code> relationship
(<code class="docutils literal notranslate"><span class="pre">Blog</span></code> to <code class="docutils literal notranslate"><span class="pre">Entry</span></code> is a one-to-many relation). We might be interested in
finding blogs that have an entry which has both <em>&quot;Lennon&quot;</em> in the headline and
was published in 2008. Or we might want to find blogs that have an entry with
<em>&quot;Lennon&quot;</em> in the headline as well as an entry that was published
in 2008. Since there are multiple entries associated with a single <code class="docutils literal notranslate"><span class="pre">Blog</span></code>,
both of these queries are possible and make sense in some situations.</p>
<p>The same type of situation arises with a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a>. For example, if an <code class="docutils literal notranslate"><span class="pre">Entry</span></code> has a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> called <code class="docutils literal notranslate"><span class="pre">tags</span></code>, we might want to
find entries linked to tags called <em>&quot;music&quot;</em> and <em>&quot;bands&quot;</em> or we might want an
entry that contains a tag with a name of <em>&quot;music&quot;</em> and a status of <em>&quot;public&quot;</em>.</p>
<p>To handle both of these situations, Django has a consistent way of processing
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> calls. Everything inside a
single <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> call is applied
simultaneously to filter out items matching all those requirements. Successive
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> calls further restrict the set
of objects, but for multi-valued relations, they apply to any object linked to
the primary model, not necessarily those objects that were selected by an
earlier <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> call.</p>
<p>That may sound a bit confusing, so hopefully an example will clarify. To
select all blogs that contain entries with both <em>&quot;Lennon&quot;</em> in the headline
and that were published in 2008 (the same entry satisfying both conditions),
we would write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">,</span> <span class="n">entry__pub_date__year</span><span class="o">=</span><span class="mi">2008</span><span class="p">)</span>
</pre></div>
</div>
<p>To select all blogs that contain an entry with <em>&quot;Lennon&quot;</em> in the headline
<strong>as well as</strong> an entry that was published in 2008, we would write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">entry__pub_date__year</span><span class="o">=</span><span class="mi">2008</span><span class="p">)</span>
</pre></div>
</div>
<p>Suppose there is only one blog that had both entries containing <em>&quot;Lennon&quot;</em> and
entries from 2008, but that none of the entries from 2008 contained <em>&quot;Lennon&quot;</em>.
The first query would not return any blogs, but the second query would return
that one blog.</p>
<p>In the second example, the first filter restricts the queryset to all those
blogs linked to entries with <em>&quot;Lennon&quot;</em> in the headline. The second filter
restricts the set of blogs <em>further</em> to those that are also linked to entries
that were published in 2008. The entries selected by the second filter may or
may not be the same as the entries in the first filter. We are filtering the
<code class="docutils literal notranslate"><span class="pre">Blog</span></code> items with each filter statement, not the <code class="docutils literal notranslate"><span class="pre">Entry</span></code> items.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>The behavior of <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> for queries
that span multi-value relationships, as described above, is not implemented
equivalently for <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a>. Instead,
the conditions in a single <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a>
call will not necessarily refer to the same item.</p>
<p>For example, the following query would exclude blogs that contain <em>both</em>
entries with <em>&quot;Lennon&quot;</em> in the headline <em>and</em> entries published in 2008:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span>
    <span class="n">entry__headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">,</span>
    <span class="n">entry__pub_date__year</span><span class="o">=</span><span class="mi">2008</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p>However, unlike the behavior when using
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a>, this will not limit blogs
based on entries that satisfy both conditions. In order to do that, i.e.
to select all blogs that do not contain entries published with <em>&quot;Lennon&quot;</em>
that were published in 2008, you need to make two queries:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span>
    <span class="n">entry__in</span><span class="o">=</span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
        <span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">,</span>
        <span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2008</span><span class="p">,</span>
    <span class="p">),</span>
<span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="s-filters-can-reference-fields-on-the-model">
<span id="s-using-f-expressions-in-filters"></span><span id="filters-can-reference-fields-on-the-model"></span><span id="using-f-expressions-in-filters"></span><h3>Filters can reference fields on the model<a class="headerlink" href="#filters-can-reference-fields-on-the-model" title="永久链接至标题">¶</a></h3>
<p>In the examples given so far, we have constructed filters that compare
the value of a model field with a constant. But what if you want to compare
the value of a model field with another field on the same model?</p>
<p>Django provides <a class="reference internal" href="../../ref/models/expressions.html#django.db.models.F" title="django.db.models.F"><code class="xref py py-class docutils literal notranslate"><span class="pre">F</span> <span class="pre">expressions</span></code></a> to allow such
comparisons. Instances of <code class="docutils literal notranslate"><span class="pre">F()</span></code> act as a reference to a model field within a
query. These references can then be used in query filters to compare the values
of two different fields on the same model instance.</p>
<p>For example, to find a list of all blog entries that have had more comments
than pingbacks, we construct an <code class="docutils literal notranslate"><span class="pre">F()</span></code> object to reference the pingback count,
and use that <code class="docutils literal notranslate"><span class="pre">F()</span></code> object in the query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">F</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">number_of_comments__gt</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;number_of_pingbacks&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>Django supports the use of addition, subtraction, multiplication,
division, modulo, and power arithmetic with <code class="docutils literal notranslate"><span class="pre">F()</span></code> objects, both with constants
and with other <code class="docutils literal notranslate"><span class="pre">F()</span></code> objects. To find all the blog entries with more than
<em>twice</em> as many comments as pingbacks, we modify the query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">number_of_comments__gt</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;number_of_pingbacks&#39;</span><span class="p">)</span> <span class="o">*</span> <span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>To find all the entries where the rating of the entry is less than the
sum of the pingback count and comment count, we would issue the
query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">rating__lt</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;number_of_comments&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">F</span><span class="p">(</span><span class="s1">&#39;number_of_pingbacks&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>You can also use the double underscore notation to span relationships in
an <code class="docutils literal notranslate"><span class="pre">F()</span></code> object. An <code class="docutils literal notranslate"><span class="pre">F()</span></code> object with a double underscore will introduce
any joins needed to access the related object. For example, to retrieve all
the entries where the author's name is the same as the blog name, we could
issue the query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">authors__name</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;blog__name&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>For date and date/time fields, you can add or subtract a
<a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object. The following would return all entries
that were modified more than 3 days after they were published:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">timedelta</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">mod_date__gt</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;pub_date&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">3</span><span class="p">))</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">F()</span></code> objects support bitwise operations by <code class="docutils literal notranslate"><span class="pre">.bitand()</span></code>, <code class="docutils literal notranslate"><span class="pre">.bitor()</span></code>,
<code class="docutils literal notranslate"><span class="pre">.bitxor()</span></code>, <code class="docutils literal notranslate"><span class="pre">.bitrightshift()</span></code>, and <code class="docutils literal notranslate"><span class="pre">.bitleftshift()</span></code>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;somefield&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">bitand</span><span class="p">(</span><span class="mi">16</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition-oracle admonition">
<p class="first admonition-title">Oracle</p>
<p class="last">Oracle doesn't support bitwise XOR operation.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>Support for <code class="docutils literal notranslate"><span class="pre">.bitxor()</span></code> was added.</p>
</div>
</div>
<div class="section" id="s-expressions-can-reference-transforms">
<span id="s-using-transforms-in-expressions"></span><span id="expressions-can-reference-transforms"></span><span id="using-transforms-in-expressions"></span><h3>Expressions can reference transforms<a class="headerlink" href="#expressions-can-reference-transforms" title="永久链接至标题">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p>Django supports using transforms in expressions.</p>
<p>For example, to find all <code class="docutils literal notranslate"><span class="pre">Entry</span></code> objects published in the same year as they
were last modified:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;mod_date__year&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>To find the earliest year an entry was published, we can issue the query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">aggregate</span><span class="p">(</span><span class="n">first_published_year</span><span class="o">=</span><span class="n">Min</span><span class="p">(</span><span class="s1">&#39;pub_date__year&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>This example finds the value of the highest rated entry and the total number
of comments on all entries for each year:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;pub_date__year&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">top_rating</span><span class="o">=</span><span class="n">Subquery</span><span class="p">(</span>
<span class="gp">... </span>        <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span>
<span class="gp">... </span>            <span class="n">pub_date__year</span><span class="o">=</span><span class="n">OuterRef</span><span class="p">(</span><span class="s1">&#39;pub_date__year&#39;</span><span class="p">),</span>
<span class="gp">... </span>        <span class="p">)</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s1">&#39;-rating&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">values</span><span class="p">(</span><span class="s1">&#39;rating&#39;</span><span class="p">)[:</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">... </span>    <span class="p">),</span>
<span class="gp">... </span>    <span class="n">total_comments</span><span class="o">=</span><span class="n">Sum</span><span class="p">(</span><span class="s1">&#39;number_of_comments&#39;</span><span class="p">),</span>
<span class="gp">... </span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-the-pk-lookup-shortcut">
<span id="the-pk-lookup-shortcut"></span><h3>The <code class="docutils literal notranslate"><span class="pre">pk</span></code> lookup shortcut<a class="headerlink" href="#the-pk-lookup-shortcut" title="永久链接至标题">¶</a></h3>
<p>For convenience, Django provides a <code class="docutils literal notranslate"><span class="pre">pk</span></code> lookup shortcut, which stands for
&quot;primary key&quot;.</p>
<p>In the example <code class="docutils literal notranslate"><span class="pre">Blog</span></code> model, the primary key is the <code class="docutils literal notranslate"><span class="pre">id</span></code> field, so these
three statements are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">id__exact</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span> <span class="c1"># Explicit form</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span> <span class="c1"># __exact is implied</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span> <span class="c1"># pk implies id__exact</span>
</pre></div>
</div>
<p>The use of <code class="docutils literal notranslate"><span class="pre">pk</span></code> isn't limited to <code class="docutils literal notranslate"><span class="pre">__exact</span></code> queries -- any query term
can be combined with <code class="docutils literal notranslate"><span class="pre">pk</span></code> to perform a query on the primary key of a model:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Get blogs entries with id 1, 4 and 7</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pk__in</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">7</span><span class="p">])</span>

<span class="c1"># Get all blog entries with id &gt; 14</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pk__gt</span><span class="o">=</span><span class="mi">14</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">pk</span></code> lookups also work across joins. For example, these three statements are
equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__id__exact</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span> <span class="c1"># Explicit form</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__id</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>        <span class="c1"># __exact is implied</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog__pk</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>        <span class="c1"># __pk implies __id__exact</span>
</pre></div>
</div>
</div>
<div class="section" id="s-escaping-percent-signs-and-underscores-in-like-statements">
<span id="escaping-percent-signs-and-underscores-in-like-statements"></span><h3>Escaping percent signs and underscores in <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> statements<a class="headerlink" href="#escaping-percent-signs-and-underscores-in-like-statements" title="永久链接至标题">¶</a></h3>
<p>The field lookups that equate to <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> SQL statements (<code class="docutils literal notranslate"><span class="pre">iexact</span></code>,
<code class="docutils literal notranslate"><span class="pre">contains</span></code>, <code class="docutils literal notranslate"><span class="pre">icontains</span></code>, <code class="docutils literal notranslate"><span class="pre">startswith</span></code>, <code class="docutils literal notranslate"><span class="pre">istartswith</span></code>, <code class="docutils literal notranslate"><span class="pre">endswith</span></code>
and <code class="docutils literal notranslate"><span class="pre">iendswith</span></code>) will automatically escape the two special characters used in
<code class="docutils literal notranslate"><span class="pre">LIKE</span></code> statements -- the percent sign and the underscore. (In a <code class="docutils literal notranslate"><span class="pre">LIKE</span></code>
statement, the percent sign signifies a multiple-character wildcard and the
underscore signifies a single-character wildcard.)</p>
<p>This means things should work intuitively, so the abstraction doesn't leak.
For example, to retrieve all the entries that contain a percent sign, use the
percent sign as any other character:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;%&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Django takes care of the quoting for you; the resulting SQL will look something
like this:</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="p">...</span> <span class="k">WHERE</span> <span class="n">headline</span> <span class="k">LIKE</span> <span class="s1">&#39;%\%%&#39;</span><span class="p">;</span>
</pre></div>
</div>
<p>Same goes for underscores. Both percentage signs and underscores are handled
for you transparently.</p>
</div>
<div class="section" id="s-caching-and-querysets">
<span id="s-id7"></span><span id="caching-and-querysets"></span><span id="id7"></span><h3>Caching and <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s<a class="headerlink" href="#caching-and-querysets" title="永久链接至标题">¶</a></h3>
<p>Each <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> contains a cache to minimize
database access. Understanding how it works will allow you to write the most
efficient code.</p>
<p>In a newly created <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>, the cache is
empty. The first time a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> is evaluated
-- and, hence, a database query happens -- Django saves the query results in
the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>’s cache and returns the results
that have been explicitly requested (e.g., the next element, if the
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> is being iterated over). Subsequent
evaluations of the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> reuse the cached
results.</p>
<p>Keep this caching behavior in mind, because it may bite you if you don't use
your <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>s correctly. For example, the
following will create two <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>s, evaluate
them, and throw them away:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">([</span><span class="n">e</span><span class="o">.</span><span class="n">headline</span> <span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">([</span><span class="n">e</span><span class="o">.</span><span class="n">pub_date</span> <span class="k">for</span> <span class="n">e</span> <span class="ow">in</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()])</span>
</pre></div>
</div>
<p>That means the same database query will be executed twice, effectively doubling
your database load. Also, there's a possibility the two lists may not include
the same database records, because an <code class="docutils literal notranslate"><span class="pre">Entry</span></code> may have been added or deleted
in the split second between the two requests.</p>
<p>To avoid this problem, save the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> and
reuse it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">([</span><span class="n">p</span><span class="o">.</span><span class="n">headline</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">queryset</span><span class="p">])</span> <span class="c1"># Evaluate the query set.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">([</span><span class="n">p</span><span class="o">.</span><span class="n">pub_date</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">queryset</span><span class="p">])</span> <span class="c1"># Re-use the cache from the evaluation.</span>
</pre></div>
</div>
<div class="section" id="s-when-querysets-are-not-cached">
<span id="when-querysets-are-not-cached"></span><h4>When <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are not cached<a class="headerlink" href="#when-querysets-are-not-cached" title="永久链接至标题">¶</a></h4>
<p>Querysets do not always cache their results.  When evaluating only <em>part</em> of
the queryset, the cache is checked, but if it is not populated then the items
returned by the subsequent query are not cached. Specifically, this means that
<a class="reference internal" href="#limiting-querysets"><span class="std std-ref">limiting the queryset</span></a> using an array slice or an
index will not populate the cache.</p>
<p>For example, repeatedly getting a certain index in a queryset object will query
the database each time:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">queryset</span><span class="p">[</span><span class="mi">5</span><span class="p">])</span> <span class="c1"># Queries the database</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">queryset</span><span class="p">[</span><span class="mi">5</span><span class="p">])</span> <span class="c1"># Queries the database again</span>
</pre></div>
</div>
<p>However, if the entire queryset has already been evaluated, the cache will be
checked instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">queryset</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">entry</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">queryset</span><span class="p">]</span> <span class="c1"># Queries the database</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">queryset</span><span class="p">[</span><span class="mi">5</span><span class="p">])</span> <span class="c1"># Uses cache</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">queryset</span><span class="p">[</span><span class="mi">5</span><span class="p">])</span> <span class="c1"># Uses cache</span>
</pre></div>
</div>
<p>Here are some examples of other actions that will result in the entire queryset
being evaluated and therefore populate the cache:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">entry</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">queryset</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">(</span><span class="n">queryset</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entry</span> <span class="ow">in</span> <span class="n">queryset</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">queryset</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">Simply printing the queryset will not populate the cache. This is because
the call to <code class="docutils literal notranslate"><span class="pre">__repr__()</span></code> only returns a slice of the entire queryset.</p>
</div>
</div>
</div>
</div>
<div class="section" id="s-querying-jsonfield">
<span id="s-id8"></span><span id="querying-jsonfield"></span><span id="id8"></span><h2>Querying <code class="docutils literal notranslate"><span class="pre">JSONField</span></code><a class="headerlink" href="#querying-jsonfield" title="永久链接至标题">¶</a></h2>
<p>Lookups implementation is different in <a class="reference internal" href="../../ref/models/fields.html#django.db.models.JSONField" title="django.db.models.JSONField"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONField</span></code></a>,
mainly due to the existence of key transformations. To demonstrate, we will use
the following example model:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Dog</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">JSONField</span><span class="p">(</span><span class="n">null</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>
</pre></div>
</div>
<div class="section" id="s-storing-and-querying-for-none">
<span id="storing-and-querying-for-none"></span><h3>Storing and querying for <code class="docutils literal notranslate"><span class="pre">None</span></code><a class="headerlink" href="#storing-and-querying-for-none" title="永久链接至标题">¶</a></h3>
<p>As with other fields, storing <code class="docutils literal notranslate"><span class="pre">None</span></code> as the field's value will store it as
SQL <code class="docutils literal notranslate"><span class="pre">NULL</span></code>. While not recommended, it is possible to store JSON scalar
<code class="docutils literal notranslate"><span class="pre">null</span></code> instead of SQL <code class="docutils literal notranslate"><span class="pre">NULL</span></code> by using <a class="reference internal" href="../../ref/models/expressions.html#django.db.models.Value" title="django.db.models.Value"><code class="xref py py-class docutils literal notranslate"><span class="pre">Value('null')</span></code></a>.</p>
<p>Whichever of the values is stored, when retrieved from the database, the Python
representation of the JSON scalar <code class="docutils literal notranslate"><span class="pre">null</span></code> is the same as SQL <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, i.e.
<code class="docutils literal notranslate"><span class="pre">None</span></code>. Therefore, it can be hard to distinguish between them.</p>
<p>This only applies to <code class="docutils literal notranslate"><span class="pre">None</span></code> as the top-level value of the field. If <code class="docutils literal notranslate"><span class="pre">None</span></code>
is inside a <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#list" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> or <a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#dict" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, it will always be interpreted
as JSON <code class="docutils literal notranslate"><span class="pre">null</span></code>.</p>
<p>When querying, <code class="docutils literal notranslate"><span class="pre">None</span></code> value will always be interpreted as JSON <code class="docutils literal notranslate"><span class="pre">null</span></code>. To
query for SQL <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, use <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-isnull"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">isnull</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Max&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>  <span class="c1"># SQL NULL.</span>
<span class="go">&lt;Dog: Max&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Archie&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;null&#39;</span><span class="p">))</span>  <span class="c1"># JSON null.</span>
<span class="go">&lt;Dog: Archie&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Archie&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data</span><span class="o">=</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;null&#39;</span><span class="p">))</span>
<span class="go">&lt;QuerySet [&lt;Dog: Archie&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__isnull</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Max&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__isnull</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Archie&gt;]&gt;</span>
</pre></div>
</div>
<p>Unless you are sure you wish to work with SQL <code class="docutils literal notranslate"><span class="pre">NULL</span></code> values, consider setting
<code class="docutils literal notranslate"><span class="pre">null=False</span></code> and providing a suitable default for empty values, such as
<code class="docutils literal notranslate"><span class="pre">default=dict</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">Storing JSON scalar <code class="docutils literal notranslate"><span class="pre">null</span></code> does not violate <a class="reference internal" href="../../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><code class="xref py py-attr docutils literal notranslate"><span class="pre">null=False</span></code></a>.</p>
</div>
</div>
<div class="section" id="s-key-index-and-path-transforms">
<span id="s-std:fieldlookup-jsonfield.key"></span><span id="key-index-and-path-transforms"></span><span id="std:fieldlookup-jsonfield.key"></span><h3>Key, index, and path transforms<a class="headerlink" href="#key-index-and-path-transforms" title="永久链接至标题">¶</a></h3>
<p>To query based on a given dictionary key, use that key as the lookup name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Rufus&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span>
<span class="gp">... </span>    <span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;labrador&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="p">{</span>
<span class="gp">... </span>        <span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">,</span>
<span class="gp">... </span>        <span class="s1">&#39;other_pets&#39;</span><span class="p">:</span> <span class="p">[{</span>
<span class="gp">... </span>            <span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Fishy&#39;</span><span class="p">,</span>
<span class="gp">... </span>        <span class="p">}],</span>
<span class="gp">... </span>    <span class="p">},</span>
<span class="gp">... </span><span class="p">})</span>
<span class="go">&lt;Dog: Rufus&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Meg&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="kc">None</span><span class="p">})</span>
<span class="go">&lt;Dog: Meg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__breed</span><span class="o">=</span><span class="s1">&#39;collie&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Meg&gt;]&gt;</span>
</pre></div>
</div>
<p>Multiple keys can be chained together to form a path lookup:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__owner__name</span><span class="o">=</span><span class="s1">&#39;Bob&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Rufus&gt;]&gt;</span>
</pre></div>
</div>
<p>If the key is an integer, it will be interpreted as an index transform in an
array:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__owner__other_pets__0__name</span><span class="o">=</span><span class="s1">&#39;Fishy&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Rufus&gt;]&gt;</span>
</pre></div>
</div>
<p>If the key you wish to query by clashes with the name of another lookup, use
the <a class="reference internal" href="#std:fieldlookup-jsonfield.contains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">contains</span></code></a> lookup instead.</p>
<p>To query for missing keys, use the <code class="docutils literal notranslate"><span class="pre">isnull</span></code> lookup:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Shep&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Shep&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__owner__isnull</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Shep&gt;]&gt;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">The lookup examples given above implicitly use the <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-exact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">exact</span></code></a> lookup.
Key, index, and path transforms can also be chained with:
<a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-icontains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">icontains</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-endswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">endswith</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-iendswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iendswith</span></code></a>,
<a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-iexact"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iexact</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-regex"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">regex</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-iregex"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">iregex</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-startswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">startswith</span></code></a>,
<a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-istartswith"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">istartswith</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-lt"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">lt</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-lte"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">lte</span></code></a>, <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-gt"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">gt</span></code></a>, and
<a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-gte"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">gte</span></code></a>, as well as with <a class="reference internal" href="#containment-and-key-lookups"><span class="std std-ref">Containment and key lookups</span></a>.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">Due to the way in which key-path queries work,
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a> and
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> are not guaranteed to
produce exhaustive sets. If you want to include objects that do not have
the path, add the <code class="docutils literal notranslate"><span class="pre">isnull</span></code> lookup.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">Since any string could be a key in a JSON object, any lookup other than
those listed below will be interpreted as a key lookup. No errors are
raised. Be extra careful for typing mistakes, and always check your queries
work as you intend.</p>
</div>
<div class="admonition-mariadb-and-oracle-users admonition">
<p class="first admonition-title">MariaDB and Oracle users</p>
<p class="last">Using <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.order_by" title="django.db.models.query.QuerySet.order_by"><code class="xref py py-meth docutils literal notranslate"><span class="pre">order_by()</span></code></a> on key, index, or
path transforms will sort the objects using the string representation of
the values. This is because MariaDB and Oracle Database do not provide a
function that converts JSON values into their equivalent SQL values.</p>
</div>
<div class="admonition-oracle-users admonition">
<p class="first admonition-title">Oracle users</p>
<p class="last">On Oracle Database, using <code class="docutils literal notranslate"><span class="pre">None</span></code> as the lookup value in an
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a> query will return objects
that do not have <code class="docutils literal notranslate"><span class="pre">null</span></code> as the value at the given path, including objects
that do not have the path. On other database backends, the query will
return objects that have the path and the value is not <code class="docutils literal notranslate"><span class="pre">null</span></code>.</p>
</div>
<div class="admonition-postgresql-users admonition">
<p class="first admonition-title">PostgreSQL users</p>
<p class="last">On PostgreSQL, if only one key or index is used, the SQL operator <code class="docutils literal notranslate"><span class="pre">-&gt;</span></code> is
used. If multiple operators are used then the <code class="docutils literal notranslate"><span class="pre">#&gt;</span></code> operator is used.</p>
</div>
</div>
<div class="section" id="s-containment-and-key-lookups">
<span id="s-id9"></span><span id="containment-and-key-lookups"></span><span id="id9"></span><h3>Containment and key lookups<a class="headerlink" href="#containment-and-key-lookups" title="永久链接至标题">¶</a></h3>
<div class="section" id="s-contains">
<span id="s-std:fieldlookup-jsonfield.contains"></span><span id="contains"></span><span id="std:fieldlookup-jsonfield.contains"></span><h4><code class="docutils literal notranslate"><span class="pre">contains</span></code><a class="headerlink" href="#contains" title="永久链接至标题">¶</a></h4>
<p>The <a class="reference internal" href="../../ref/models/querysets.html#std:fieldlookup-contains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">contains</span></code></a> lookup is overridden on <code class="docutils literal notranslate"><span class="pre">JSONField</span></code>. The returned
objects are those where the given <code class="docutils literal notranslate"><span class="pre">dict</span></code> of key-value pairs are all
contained in the top-level of the field. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Rufus&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;labrador&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Rufus&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Meg&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Meg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Fred&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{})</span>
<span class="go">&lt;Dog: Fred&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__contains</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;QuerySet [&lt;Dog: Rufus&gt;, &lt;Dog: Meg&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__contains</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">})</span>
<span class="go">&lt;QuerySet [&lt;Dog: Meg&gt;]&gt;</span>
</pre></div>
</div>
<div class="admonition-oracle-and-sqlite admonition">
<p class="first admonition-title">Oracle and SQLite</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">contains</span></code> is not supported on Oracle and SQLite.</p>
</div>
</div>
<div class="section" id="s-contained-by">
<span id="s-std:fieldlookup-jsonfield.contained_by"></span><span id="contained-by"></span><span id="std:fieldlookup-jsonfield.contained_by"></span><h4><code class="docutils literal notranslate"><span class="pre">contained_by</span></code><a class="headerlink" href="#contained-by" title="永久链接至标题">¶</a></h4>
<p>This is the inverse of the <a class="reference internal" href="#std:fieldlookup-jsonfield.contains"><code class="xref std std-lookup docutils literal notranslate"><span class="pre">contains</span></code></a> lookup - the
objects returned will be those where the key-value pairs on the object are a
subset of those in the value passed. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Rufus&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;labrador&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Rufus&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Meg&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Meg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Fred&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{})</span>
<span class="go">&lt;Dog: Fred&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__contained_by</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;QuerySet [&lt;Dog: Meg&gt;, &lt;Dog: Fred&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__contained_by</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">})</span>
<span class="go">&lt;QuerySet [&lt;Dog: Fred&gt;]&gt;</span>
</pre></div>
</div>
<div class="admonition-oracle-and-sqlite admonition">
<p class="first admonition-title">Oracle and SQLite</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">contained_by</span></code> is not supported on Oracle and SQLite.</p>
</div>
</div>
<div class="section" id="s-has-key">
<span id="s-std:fieldlookup-jsonfield.has_key"></span><span id="has-key"></span><span id="std:fieldlookup-jsonfield.has_key"></span><h4><code class="docutils literal notranslate"><span class="pre">has_key</span></code><a class="headerlink" href="#has-key" title="永久链接至标题">¶</a></h4>
<p>Returns objects where the given key is in the top-level of the data. For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Rufus&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;labrador&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Rufus&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Meg&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Meg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__has_key</span><span class="o">=</span><span class="s1">&#39;owner&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;Dog: Meg&gt;]&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-has-keys">
<span id="s-std:fieldlookup-jsonfield.has_any_keys"></span><span id="has-keys"></span><span id="std:fieldlookup-jsonfield.has_any_keys"></span><h4><code class="docutils literal notranslate"><span class="pre">has_keys</span></code><a class="headerlink" href="#has-keys" title="永久链接至标题">¶</a></h4>
<p>Returns objects where all of the given keys are in the top-level of the data.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Rufus&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;labrador&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Rufus&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Meg&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;collie&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Meg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__has_keys</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;breed&#39;</span><span class="p">,</span> <span class="s1">&#39;owner&#39;</span><span class="p">])</span>
<span class="go">&lt;QuerySet [&lt;Dog: Meg&gt;]&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-has-any-keys">
<span id="s-std:fieldlookup-jsonfield.has_keys"></span><span id="has-any-keys"></span><span id="std:fieldlookup-jsonfield.has_keys"></span><h4><code class="docutils literal notranslate"><span class="pre">has_any_keys</span></code><a class="headerlink" href="#has-any-keys" title="永久链接至标题">¶</a></h4>
<p>Returns objects where any of the given keys are in the top-level of the data.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Rufus&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;breed&#39;</span><span class="p">:</span> <span class="s1">&#39;labrador&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Rufus&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Meg&#39;</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="s1">&#39;Bob&#39;</span><span class="p">})</span>
<span class="go">&lt;Dog: Meg&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Dog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">data__has_any_keys</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;owner&#39;</span><span class="p">,</span> <span class="s1">&#39;breed&#39;</span><span class="p">])</span>
<span class="go">&lt;QuerySet [&lt;Dog: Rufus&gt;, &lt;Dog: Meg&gt;]&gt;</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="s-complex-lookups-with-q-objects">
<span id="s-complex-lookups-with-q"></span><span id="complex-lookups-with-q-objects"></span><span id="complex-lookups-with-q"></span><h2>Complex lookups with <code class="docutils literal notranslate"><span class="pre">Q</span></code> objects<a class="headerlink" href="#complex-lookups-with-q-objects" title="永久链接至标题">¶</a></h2>
<p>Keyword argument queries -- in <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a>,
etc. -- are &quot;AND&quot;ed together. If you need to execute more complex queries (for
example, queries with <code class="docutils literal notranslate"><span class="pre">OR</span></code> statements), you can use <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span> <span class="pre">objects</span></code></a>.</p>
<p>A <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.Q" title="django.db.models.Q"><code class="xref py py-class docutils literal notranslate"><span class="pre">Q</span> <span class="pre">object</span></code></a> (<code class="docutils literal notranslate"><span class="pre">django.db.models.Q</span></code>) is an object
used to encapsulate a collection of keyword arguments. These keyword arguments
are specified as in &quot;Field lookups&quot; above.</p>
<p>For example, this <code class="docutils literal notranslate"><span class="pre">Q</span></code> object encapsulates a single <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db.models</span> <span class="kn">import</span> <span class="n">Q</span>
<span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s1">&#39;What&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">Q</span></code> objects can be combined using the <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> and <code class="docutils literal notranslate"><span class="pre">|</span></code> operators. When an
operator is used on two <code class="docutils literal notranslate"><span class="pre">Q</span></code> objects, it yields a new <code class="docutils literal notranslate"><span class="pre">Q</span></code> object.</p>
<p>For example, this statement yields a single <code class="docutils literal notranslate"><span class="pre">Q</span></code> object that represents the
&quot;OR&quot; of two <code class="docutils literal notranslate"><span class="pre">&quot;question__startswith&quot;</span></code> queries:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s1">&#39;Who&#39;</span><span class="p">)</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s1">&#39;What&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This is equivalent to the following SQL <code class="docutils literal notranslate"><span class="pre">WHERE</span></code> clause:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">WHERE</span> <span class="n">question</span> <span class="n">LIKE</span> <span class="s1">&#39;Who%&#39;</span> <span class="n">OR</span> <span class="n">question</span> <span class="n">LIKE</span> <span class="s1">&#39;What%&#39;</span>
</pre></div>
</div>
<p>You can compose statements of arbitrary complexity by combining <code class="docutils literal notranslate"><span class="pre">Q</span></code> objects
with the <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> and <code class="docutils literal notranslate"><span class="pre">|</span></code> operators and use parenthetical grouping. Also, <code class="docutils literal notranslate"><span class="pre">Q</span></code>
objects can be negated using the <code class="docutils literal notranslate"><span class="pre">~</span></code> operator, allowing for combined lookups
that combine both a normal query and a negated (<code class="docutils literal notranslate"><span class="pre">NOT</span></code>) query:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s1">&#39;Who&#39;</span><span class="p">)</span> <span class="o">|</span> <span class="o">~</span><span class="n">Q</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2005</span><span class="p">)</span>
</pre></div>
</div>
<p>Each lookup function that takes keyword-arguments
(e.g. <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.filter" title="django.db.models.query.QuerySet.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a>,
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.exclude" title="django.db.models.query.QuerySet.exclude"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exclude()</span></code></a>,
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>) can also be passed one or more
<code class="docutils literal notranslate"><span class="pre">Q</span></code> objects as positional (not-named) arguments. If you provide multiple
<code class="docutils literal notranslate"><span class="pre">Q</span></code> object arguments to a lookup function, the arguments will be &quot;AND&quot;ed
together. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">question__startswith</span><span class="o">=</span><span class="s1">&#39;Who&#39;</span><span class="p">),</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">))</span>
<span class="p">)</span>
</pre></div>
</div>
<p>... roughly translates into the SQL:</p>
<div class="highlight-sql notranslate"><div class="highlight"><pre><span></span><span class="k">SELECT</span> <span class="o">*</span> <span class="k">from</span> <span class="n">polls</span> <span class="k">WHERE</span> <span class="n">question</span> <span class="k">LIKE</span> <span class="s1">&#39;Who%&#39;</span>
    <span class="k">AND</span> <span class="p">(</span><span class="n">pub_date</span> <span class="o">=</span> <span class="s1">&#39;2005-05-02&#39;</span> <span class="k">OR</span> <span class="n">pub_date</span> <span class="o">=</span> <span class="s1">&#39;2005-05-06&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Lookup functions can mix the use of <code class="docutils literal notranslate"><span class="pre">Q</span></code> objects and keyword arguments. All
arguments provided to a lookup function (be they keyword arguments or <code class="docutils literal notranslate"><span class="pre">Q</span></code>
objects) are &quot;AND&quot;ed together. However, if a <code class="docutils literal notranslate"><span class="pre">Q</span></code> object is provided, it must
precede the definition of any keyword arguments. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">)),</span>
    <span class="n">question__startswith</span><span class="o">=</span><span class="s1">&#39;Who&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p>... would be a valid query, equivalent to the previous example; but:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># INVALID QUERY</span>
<span class="n">Poll</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span>
    <span class="n">question__startswith</span><span class="o">=</span><span class="s1">&#39;Who&#39;</span><span class="p">,</span>
    <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="o">|</span> <span class="n">Q</span><span class="p">(</span><span class="n">pub_date</span><span class="o">=</span><span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">))</span>
<span class="p">)</span>
</pre></div>
</div>
<p>... would not be valid.</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">The <a class="reference external" href="https://github.com/django/django/blob/main/tests/or_lookups/tests.py">OR lookups examples</a> in Django's
unit tests show some possible uses of <code class="docutils literal notranslate"><span class="pre">Q</span></code>.</p>
</div>
</div>
<div class="section" id="s-comparing-objects">
<span id="comparing-objects"></span><h2>Comparing objects<a class="headerlink" href="#comparing-objects" title="永久链接至标题">¶</a></h2>
<p>To compare two model instances, use the standard Python comparison operator,
the double equals sign: <code class="docutils literal notranslate"><span class="pre">==</span></code>. Behind the scenes, that compares the primary
key values of two models.</p>
<p>Using the <code class="docutils literal notranslate"><span class="pre">Entry</span></code> example above, the following two statements are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">some_entry</span> <span class="o">==</span> <span class="n">other_entry</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">some_entry</span><span class="o">.</span><span class="n">id</span> <span class="o">==</span> <span class="n">other_entry</span><span class="o">.</span><span class="n">id</span>
</pre></div>
</div>
<p>If a model's primary key isn't called <code class="docutils literal notranslate"><span class="pre">id</span></code>, no problem. Comparisons will
always use the primary key, whatever it's called. For example, if a model's
primary key field is called <code class="docutils literal notranslate"><span class="pre">name</span></code>, these two statements are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">some_obj</span> <span class="o">==</span> <span class="n">other_obj</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">some_obj</span><span class="o">.</span><span class="n">name</span> <span class="o">==</span> <span class="n">other_obj</span><span class="o">.</span><span class="n">name</span>
</pre></div>
</div>
</div>
<div class="section" id="s-deleting-objects">
<span id="s-topics-db-queries-delete"></span><span id="deleting-objects"></span><span id="topics-db-queries-delete"></span><h2>Deleting objects<a class="headerlink" href="#deleting-objects" title="永久链接至标题">¶</a></h2>
<p>The delete method, conveniently, is named
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.delete" title="django.db.models.Model.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete()</span></code></a>. This method immediately deletes the
object and returns the number of objects deleted and a dictionary with
the number of deletions per object type. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go">(1, {&#39;weblog.Entry&#39;: 1})</span>
</pre></div>
</div>
<p>You can also delete objects in bulk. Every
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> has a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.delete" title="django.db.models.query.QuerySet.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete()</span></code></a> method, which deletes all
members of that <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>.</p>
<p>For example, this deletes all <code class="docutils literal notranslate"><span class="pre">Entry</span></code> objects with a <code class="docutils literal notranslate"><span class="pre">pub_date</span></code> year of
2005:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2005</span><span class="p">)</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="go">(5, {&#39;webapp.Entry&#39;: 5})</span>
</pre></div>
</div>
<p>Keep in mind that this will, whenever possible, be executed purely in SQL, and
so the <code class="docutils literal notranslate"><span class="pre">delete()</span></code> methods of individual object instances will not necessarily
be called during the process. If you've provided a custom <code class="docutils literal notranslate"><span class="pre">delete()</span></code> method
on a model class and want to ensure that it is called, you will need to
&quot;manually&quot; delete instances of that model (e.g., by iterating over a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> and calling <code class="docutils literal notranslate"><span class="pre">delete()</span></code> on each
object individually) rather than using the bulk
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.delete" title="django.db.models.query.QuerySet.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete()</span></code></a> method of a
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>.</p>
<p>When Django deletes an object, by default it emulates the behavior of the SQL
constraint <code class="docutils literal notranslate"><span class="pre">ON</span> <span class="pre">DELETE</span> <span class="pre">CASCADE</span></code> -- in other words, any objects which had
foreign keys pointing at the object to be deleted will be deleted along with
it. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="c1"># This will delete the Blog and all of its Entry objects.</span>
<span class="n">b</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
<p>This cascade behavior is customizable via the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.on_delete" title="django.db.models.ForeignKey.on_delete"><code class="xref py py-attr docutils literal notranslate"><span class="pre">on_delete</span></code></a> argument to the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>.</p>
<p>Note that <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.delete" title="django.db.models.query.QuerySet.delete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">delete()</span></code></a> is the only
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> method that is not exposed on a
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> itself. This is a safety mechanism to
prevent you from accidentally requesting <code class="docutils literal notranslate"><span class="pre">Entry.objects.delete()</span></code>, and
deleting <em>all</em> the entries. If you <em>do</em> want to delete all the objects, then
you have to explicitly request a complete query set:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-copying-model-instances">
<span id="s-topics-db-queries-copy"></span><span id="copying-model-instances"></span><span id="topics-db-queries-copy"></span><h2>Copying model instances<a class="headerlink" href="#copying-model-instances" title="永久链接至标题">¶</a></h2>
<p>Although there is no built-in method for copying model instances, it is
possible to easily create new instance with all fields' values copied. In the
simplest case, you can set <code class="docutils literal notranslate"><span class="pre">pk</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code> and
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model._state" title="django.db.models.Model._state"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_state.adding</span></code></a> to <code class="docutils literal notranslate"><span class="pre">True</span></code>. Using our
blog example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">blog</span> <span class="o">=</span> <span class="n">Blog</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;My blog&#39;</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s1">&#39;Blogging is easy&#39;</span><span class="p">)</span>
<span class="n">blog</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># blog.pk == 1</span>

<span class="n">blog</span><span class="o">.</span><span class="n">pk</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">blog</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">adding</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">blog</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># blog.pk == 2</span>
</pre></div>
</div>
<p>Things get more complicated if you use inheritance. Consider a subclass of
<code class="docutils literal notranslate"><span class="pre">Blog</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ThemeBlog</span><span class="p">(</span><span class="n">Blog</span><span class="p">):</span>
    <span class="n">theme</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">)</span>

<span class="n">django_blog</span> <span class="o">=</span> <span class="n">ThemeBlog</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Django&#39;</span><span class="p">,</span> <span class="n">tagline</span><span class="o">=</span><span class="s1">&#39;Django is easy&#39;</span><span class="p">,</span> <span class="n">theme</span><span class="o">=</span><span class="s1">&#39;python&#39;</span><span class="p">)</span>
<span class="n">django_blog</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># django_blog.pk == 3</span>
</pre></div>
</div>
<p>Due to how inheritance works, you have to set both <code class="docutils literal notranslate"><span class="pre">pk</span></code> and <code class="docutils literal notranslate"><span class="pre">id</span></code> to
<code class="docutils literal notranslate"><span class="pre">None</span></code>, and <code class="docutils literal notranslate"><span class="pre">_state.adding</span></code> to <code class="docutils literal notranslate"><span class="pre">True</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">django_blog</span><span class="o">.</span><span class="n">pk</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">django_blog</span><span class="o">.</span><span class="n">id</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">django_blog</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">adding</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">django_blog</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># django_blog.pk == 4</span>
</pre></div>
</div>
<p>This process doesn't copy relations that aren't part of the model's database
table. For example, <code class="docutils literal notranslate"><span class="pre">Entry</span></code> has a <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> to <code class="docutils literal notranslate"><span class="pre">Author</span></code>. After
duplicating an entry, you must set the many-to-many relations for the new
entry:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">entry</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># some previous entry</span>
<span class="n">old_authors</span> <span class="o">=</span> <span class="n">entry</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="n">entry</span><span class="o">.</span><span class="n">pk</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">entry</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">adding</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">entry</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="n">entry</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="n">old_authors</span><span class="p">)</span>
</pre></div>
</div>
<p>For a <code class="docutils literal notranslate"><span class="pre">OneToOneField</span></code>, you must duplicate the related object and assign it
to the new object's field to avoid violating the one-to-one unique constraint.
For example, assuming <code class="docutils literal notranslate"><span class="pre">entry</span></code> is already duplicated as above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">detail</span> <span class="o">=</span> <span class="n">EntryDetail</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">detail</span><span class="o">.</span><span class="n">pk</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">detail</span><span class="o">.</span><span class="n">_state</span><span class="o">.</span><span class="n">adding</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">detail</span><span class="o">.</span><span class="n">entry</span> <span class="o">=</span> <span class="n">entry</span>
<span class="n">detail</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-updating-multiple-objects-at-once">
<span id="s-topics-db-queries-update"></span><span id="updating-multiple-objects-at-once"></span><span id="topics-db-queries-update"></span><h2>Updating multiple objects at once<a class="headerlink" href="#updating-multiple-objects-at-once" title="永久链接至标题">¶</a></h2>
<p>Sometimes you want to set a field to a particular value for all the objects in
a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>. You can do this with the
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.update" title="django.db.models.query.QuerySet.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> method. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Update all the headlines with pub_date in 2007.</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">pub_date__year</span><span class="o">=</span><span class="mi">2007</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s1">&#39;Everything is the same&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>You can only set non-relation fields and <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>
fields using this method. To update a non-relation field, provide the new value
as a constant. To update <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> fields, set the
new value to be the new model instance you want to point to. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="go"># Change every Entry so that it belongs to this Blog.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">update()</span></code> method is applied instantly and returns the number of rows
matched by the query (which may not be equal to the number of rows updated if
some rows already have the new value). The only restriction on the
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> being updated is that it can only
access one database table: the model's main table. You can filter based on
related fields, but you can only update columns in the model's main
table. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="go"># Update all the headlines belonging to this Blog.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="p">)</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="s1">&#39;Everything is the same&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Be aware that the <code class="docutils literal notranslate"><span class="pre">update()</span></code> method is converted directly to an SQL
statement. It is a bulk operation for direct updates. It doesn't run any
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> methods on your models, or emit the
<code class="docutils literal notranslate"><span class="pre">pre_save</span></code> or <code class="docutils literal notranslate"><span class="pre">post_save</span></code> signals (which are a consequence of calling
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>), or honor the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><code class="xref py py-attr docutils literal notranslate"><span class="pre">auto_now</span></code></a> field option.
If you want to save every item in a <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a>
and make sure that the <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a> method is called on
each instance, you don't need any special function to handle that. Loop over
them and call <a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">my_queryset</span><span class="p">:</span>
    <span class="n">item</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>Calls to update can also use <a class="reference internal" href="../../ref/models/expressions.html#django.db.models.F" title="django.db.models.F"><code class="xref py py-class docutils literal notranslate"><span class="pre">F</span> <span class="pre">expressions</span></code></a> to
update one field based on the value of another field in the model. This is
especially useful for incrementing counters based upon their current value. For
example, to increment the pingback count for every entry in the blog:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">number_of_pingbacks</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;number_of_pingbacks&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>However, unlike <code class="docutils literal notranslate"><span class="pre">F()</span></code> objects in filter and exclude clauses, you can't
introduce joins when you use <code class="docutils literal notranslate"><span class="pre">F()</span></code> objects in an update -- you can only
reference fields local to the model being updated. If you attempt to introduce
a join with an <code class="docutils literal notranslate"><span class="pre">F()</span></code> object, a <code class="docutils literal notranslate"><span class="pre">FieldError</span></code> will be raised:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># This will raise a FieldError</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">headline</span><span class="o">=</span><span class="n">F</span><span class="p">(</span><span class="s1">&#39;blog__name&#39;</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="s-related-objects">
<span id="s-topics-db-queries-related"></span><span id="related-objects"></span><span id="topics-db-queries-related"></span><h2>Related objects<a class="headerlink" href="#related-objects" title="永久链接至标题">¶</a></h2>
<p>When you define a relationship in a model (i.e., a
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a>, or
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a>), instances of that model will have
a convenient API to access the related object(s).</p>
<p>Using the models at the top of this page, for example, an <code class="docutils literal notranslate"><span class="pre">Entry</span></code> object <code class="docutils literal notranslate"><span class="pre">e</span></code>
can get its associated <code class="docutils literal notranslate"><span class="pre">Blog</span></code> object by accessing the <code class="docutils literal notranslate"><span class="pre">blog</span></code> attribute:
<code class="docutils literal notranslate"><span class="pre">e.blog</span></code>.</p>
<p>(Behind the scenes, this functionality is implemented by Python
<a class="reference external" href="https://docs.python.org/3/howto/descriptor.html" title="(在 Python v3.9)"><span class="xref std std-doc">descriptors</span></a>. This shouldn't really matter to
you, but we point it out here for the curious.)</p>
<p>Django also creates API accessors for the &quot;other&quot; side of the relationship --
the link from the related model to the model that defines the relationship.
For example, a <code class="docutils literal notranslate"><span class="pre">Blog</span></code> object <code class="docutils literal notranslate"><span class="pre">b</span></code> has access to a list of all related
<code class="docutils literal notranslate"><span class="pre">Entry</span></code> objects via the <code class="docutils literal notranslate"><span class="pre">entry_set</span></code> attribute: <code class="docutils literal notranslate"><span class="pre">b.entry_set.all()</span></code>.</p>
<p>All examples in this section use the sample <code class="docutils literal notranslate"><span class="pre">Blog</span></code>, <code class="docutils literal notranslate"><span class="pre">Author</span></code> and <code class="docutils literal notranslate"><span class="pre">Entry</span></code>
models defined at the top of this page.</p>
<div class="section" id="s-one-to-many-relationships">
<span id="one-to-many-relationships"></span><h3>One-to-many relationships<a class="headerlink" href="#one-to-many-relationships" title="永久链接至标题">¶</a></h3>
<div class="section" id="s-forward">
<span id="forward"></span><h4>Forward<a class="headerlink" href="#forward" title="永久链接至标题">¶</a></h4>
<p>If a model has a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>, instances of that model
will have access to the related (foreign) object via an attribute of the model.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">blog</span> <span class="c1"># Returns the related Blog object.</span>
</pre></div>
</div>
<p>You can get and set via a foreign-key attribute. As you may expect, changes to
the foreign key aren't saved to the database until you call
<a class="reference internal" href="../../ref/models/instances.html#django.db.models.Model.save" title="django.db.models.Model.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">blog</span> <span class="o">=</span> <span class="n">some_blog</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>If a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> field has <code class="docutils literal notranslate"><span class="pre">null=True</span></code> set (i.e.,
it allows <code class="docutils literal notranslate"><span class="pre">NULL</span></code> values), you can assign <code class="docutils literal notranslate"><span class="pre">None</span></code> to remove the relation.
Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">blog</span> <span class="o">=</span> <span class="kc">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># &quot;UPDATE blog_entry SET blog_id = NULL ...;&quot;</span>
</pre></div>
</div>
<p>Forward access to one-to-many relationships is cached the first time the
related object is accessed. Subsequent accesses to the foreign key on the same
object instance are cached. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">blog</span><span class="p">)</span>  <span class="c1"># Hits the database to retrieve the associated Blog.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">blog</span><span class="p">)</span>  <span class="c1"># Doesn&#39;t hit the database; uses cached version.</span>
</pre></div>
</div>
<p>Note that the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet.select_related" title="django.db.models.query.QuerySet.select_related"><code class="xref py py-meth docutils literal notranslate"><span class="pre">select_related()</span></code></a>
<a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> method recursively prepopulates the
cache of all one-to-many relationships ahead of time. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">select_related</span><span class="p">()</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">blog</span><span class="p">)</span>  <span class="c1"># Doesn&#39;t hit the database; uses cached version.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">blog</span><span class="p">)</span>  <span class="c1"># Doesn&#39;t hit the database; uses cached version.</span>
</pre></div>
</div>
</div>
<div class="section" id="s-following-relationships-backward">
<span id="s-backwards-related-objects"></span><span id="following-relationships-backward"></span><span id="backwards-related-objects"></span><h4>Following relationships &quot;backward&quot;<a class="headerlink" href="#following-relationships-backward" title="永久链接至标题">¶</a></h4>
<p>If a model has a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>, instances of the
foreign-key model will have access to a <a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> that
returns all instances of the first model. By default, this
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> is named <code class="docutils literal notranslate"><span class="pre">FOO_set</span></code>, where <code class="docutils literal notranslate"><span class="pre">FOO</span></code> is the
source model name, lowercased. This <a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> returns
<code class="docutils literal notranslate"><span class="pre">QuerySets</span></code>, which can be filtered and manipulated as described in the
&quot;Retrieving objects&quot; section above.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c1"># Returns all Entry objects related to Blog.</span>

<span class="go"># b.entry_set is a Manager that returns QuerySets.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
</pre></div>
</div>
<p>You can override the <code class="docutils literal notranslate"><span class="pre">FOO_set</span></code> name by setting the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey.related_name" title="django.db.models.ForeignKey.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_name</span></code></a> parameter in the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> definition. For example, if the <code class="docutils literal notranslate"><span class="pre">Entry</span></code>
model was altered to <code class="docutils literal notranslate"><span class="pre">blog</span> <span class="pre">=</span> <span class="pre">ForeignKey(Blog,</span> <span class="pre">on_delete=models.CASCADE,</span>
<span class="pre">related_name='entries')</span></code>, the above example code would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entries</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c1"># Returns all Entry objects related to Blog.</span>

<span class="go"># b.entries is a Manager that returns QuerySets.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entries</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">headline__contains</span><span class="o">=</span><span class="s1">&#39;Lennon&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">entries</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-a-custom-reverse-manager">
<span id="s-using-custom-reverse-manager"></span><span id="using-a-custom-reverse-manager"></span><span id="using-custom-reverse-manager"></span><h4>Using a custom reverse manager<a class="headerlink" href="#using-a-custom-reverse-manager" title="永久链接至标题">¶</a></h4>
<p>By default the <a class="reference internal" href="../../ref/models/relations.html#django.db.models.fields.related.RelatedManager" title="django.db.models.fields.related.RelatedManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">RelatedManager</span></code></a> used
for reverse relations is a subclass of the <a class="reference internal" href="managers.html#manager-names"><span class="std std-ref">default manager</span></a>
for that model. If you would like to specify a different manager for a given
query you can use the following syntax:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Entry</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c1">#...</span>
    <span class="n">objects</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>  <span class="c1"># Default Manager</span>
    <span class="n">entries</span> <span class="o">=</span> <span class="n">EntryManager</span><span class="p">()</span>    <span class="c1"># Custom Manager</span>

<span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="p">(</span><span class="n">manager</span><span class="o">=</span><span class="s1">&#39;entries&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
</pre></div>
</div>
<p>If <code class="docutils literal notranslate"><span class="pre">EntryManager</span></code> performed default filtering in its <code class="docutils literal notranslate"><span class="pre">get_queryset()</span></code>
method, that filtering would apply to the <code class="docutils literal notranslate"><span class="pre">all()</span></code> call.</p>
<p>Specifying a custom reverse manager also enables you to call its custom
methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="p">(</span><span class="n">manager</span><span class="o">=</span><span class="s1">&#39;entries&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">is_published</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-additional-methods-to-handle-related-objects">
<span id="additional-methods-to-handle-related-objects"></span><h4>Additional methods to handle related objects<a class="headerlink" href="#additional-methods-to-handle-related-objects" title="永久链接至标题">¶</a></h4>
<p>In addition to the <a class="reference internal" href="../../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> methods defined in
&quot;Retrieving objects&quot; above, the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>
<a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> has additional methods used to handle the
set of related objects. A synopsis of each is below, and complete details can
be found in the <a class="reference internal" href="../../ref/models/relations.html"><span class="doc">related objects reference</span></a>.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">add(obj1,</span> <span class="pre">obj2,</span> <span class="pre">...)</span></code></dt>
<dd>Adds the specified model objects to the related object set.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">create(**kwargs)</span></code></dt>
<dd>Creates a new object, saves it and puts it in the related object set.
Returns the newly created object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">remove(obj1,</span> <span class="pre">obj2,</span> <span class="pre">...)</span></code></dt>
<dd>Removes the specified model objects from the related object set.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">clear()</span></code></dt>
<dd>Removes all objects from the related object set.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">set(objs)</span></code></dt>
<dd>Replace the set of related objects.</dd>
</dl>
<p>To assign the members of a related set, use the <code class="docutils literal notranslate"><span class="pre">set()</span></code> method with an
iterable of object instances. For example, if <code class="docutils literal notranslate"><span class="pre">e1</span></code> and <code class="docutils literal notranslate"><span class="pre">e2</span></code> are <code class="docutils literal notranslate"><span class="pre">Entry</span></code>
instances:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">Blog</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">b</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">set</span><span class="p">([</span><span class="n">e1</span><span class="p">,</span> <span class="n">e2</span><span class="p">])</span>
</pre></div>
</div>
<p>If the <code class="docutils literal notranslate"><span class="pre">clear()</span></code> method is available, any pre-existing objects will be
removed from the <code class="docutils literal notranslate"><span class="pre">entry_set</span></code> before all objects in the iterable (in this
case, a list) are added to the set. If the <code class="docutils literal notranslate"><span class="pre">clear()</span></code> method is <em>not</em>
available, all objects in the iterable will be added without removing any
existing elements.</p>
<p>Each &quot;reverse&quot; operation described in this section has an immediate effect on
the database. Every addition, creation and deletion is immediately and
automatically saved to the database.</p>
</div>
</div>
<div class="section" id="s-many-to-many-relationships">
<span id="s-m2m-reverse-relationships"></span><span id="many-to-many-relationships"></span><span id="m2m-reverse-relationships"></span><h3>Many-to-many relationships<a class="headerlink" href="#many-to-many-relationships" title="永久链接至标题">¶</a></h3>
<p>Both ends of a many-to-many relationship get automatic API access to the other
end. The API works similar to a &quot;backward&quot; one-to-many relationship, above.</p>
<p>One difference is in the attribute naming: The model that defines the
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> uses the attribute name of that
field itself, whereas the &quot;reverse&quot; model uses the lowercased model name of the
original model, plus <code class="docutils literal notranslate"><span class="pre">'_set'</span></code> (just like reverse one-to-many relationships).</p>
<p>An example makes this easier to understand:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="n">e</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c1"># Returns all Author objects for this Entry.</span>
<span class="n">e</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>
<span class="n">e</span><span class="o">.</span><span class="n">authors</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">name__contains</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">)</span>

<span class="n">a</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="n">a</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span> <span class="c1"># Returns all Entry objects for this Author.</span>
</pre></div>
</div>
<p>Like <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>,
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> can specify
<a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField.related_name" title="django.db.models.ManyToManyField.related_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">related_name</span></code></a>. In the above example,
if the <a class="reference internal" href="../../ref/models/fields.html#django.db.models.ManyToManyField" title="django.db.models.ManyToManyField"><code class="xref py py-class docutils literal notranslate"><span class="pre">ManyToManyField</span></code></a> in <code class="docutils literal notranslate"><span class="pre">Entry</span></code> had specified
<code class="docutils literal notranslate"><span class="pre">related_name='entries'</span></code>, then each <code class="docutils literal notranslate"><span class="pre">Author</span></code> instance would have an
<code class="docutils literal notranslate"><span class="pre">entries</span></code> attribute instead of <code class="docutils literal notranslate"><span class="pre">entry_set</span></code>.</p>
<p>Another difference from one-to-many relationships is that in addition to model
instances,  the <code class="docutils literal notranslate"><span class="pre">add()</span></code>, <code class="docutils literal notranslate"><span class="pre">set()</span></code>, and <code class="docutils literal notranslate"><span class="pre">remove()</span></code> methods on many-to-many
relationships accept primary key values. For example, if <code class="docutils literal notranslate"><span class="pre">e1</span></code> and <code class="docutils literal notranslate"><span class="pre">e2</span></code> are
<code class="docutils literal notranslate"><span class="pre">Entry</span></code> instances, then these <code class="docutils literal notranslate"><span class="pre">set()</span></code> calls work identically:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="n">Author</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="n">a</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">set</span><span class="p">([</span><span class="n">e1</span><span class="p">,</span> <span class="n">e2</span><span class="p">])</span>
<span class="n">a</span><span class="o">.</span><span class="n">entry_set</span><span class="o">.</span><span class="n">set</span><span class="p">([</span><span class="n">e1</span><span class="o">.</span><span class="n">pk</span><span class="p">,</span> <span class="n">e2</span><span class="o">.</span><span class="n">pk</span><span class="p">])</span>
</pre></div>
</div>
</div>
<div class="section" id="s-one-to-one-relationships">
<span id="one-to-one-relationships"></span><h3>One-to-one relationships<a class="headerlink" href="#one-to-one-relationships" title="永久链接至标题">¶</a></h3>
<p>One-to-one relationships are very similar to many-to-one relationships. If you
define a <a class="reference internal" href="../../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneToOneField</span></code></a> on your model, instances of
that model will have access to the related object via an attribute of the
model.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">EntryDetail</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">entry</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">OneToOneField</span><span class="p">(</span><span class="n">Entry</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">details</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">TextField</span><span class="p">()</span>

<span class="n">ed</span> <span class="o">=</span> <span class="n">EntryDetail</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="n">ed</span><span class="o">.</span><span class="n">entry</span> <span class="c1"># Returns the related Entry object.</span>
</pre></div>
</div>
<p>The difference comes in &quot;reverse&quot; queries. The related model in a one-to-one
relationship also has access to a <a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> object, but
that <a class="reference internal" href="managers.html#django.db.models.Manager" title="django.db.models.Manager"><code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code></a> represents a single object, rather than
a collection of objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">e</span> <span class="o">=</span> <span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="n">e</span><span class="o">.</span><span class="n">entrydetail</span> <span class="c1"># returns the related EntryDetail object</span>
</pre></div>
</div>
<p>If no object has been assigned to this relationship, Django will raise
a <code class="docutils literal notranslate"><span class="pre">DoesNotExist</span></code> exception.</p>
<p>Instances can be assigned to the reverse relationship in the same way as
you would assign the forward relationship:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">e</span><span class="o">.</span><span class="n">entrydetail</span> <span class="o">=</span> <span class="n">ed</span>
</pre></div>
</div>
</div>
<div class="section" id="s-how-are-the-backward-relationships-possible">
<span id="how-are-the-backward-relationships-possible"></span><h3>How are the backward relationships possible?<a class="headerlink" href="#how-are-the-backward-relationships-possible" title="永久链接至标题">¶</a></h3>
<p>Other object-relational mappers require you to define relationships on both
sides. The Django developers believe this is a violation of the DRY (Don't
Repeat Yourself) principle, so Django only requires you to define the
relationship on one end.</p>
<p>But how is this possible, given that a model class doesn't know which other
model classes are related to it until those other model classes are loaded?</p>
<p>The answer lies in the <a class="reference internal" href="../../ref/applications.html#django.apps.apps" title="django.apps.apps"><code class="xref py py-data docutils literal notranslate"><span class="pre">app</span> <span class="pre">registry</span></code></a>. When Django
starts, it imports each application listed in <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>, and
then the <code class="docutils literal notranslate"><span class="pre">models</span></code> module inside each application. Whenever a new model class
is created, Django adds backward-relationships to any related models. If the
related models haven't been imported yet, Django keeps tracks of the
relationships and adds them when the related models eventually are imported.</p>
<p>For this reason, it's particularly important that all the models you're using
be defined in applications listed in <a class="reference internal" href="../../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>. Otherwise,
backwards relations may not work properly.</p>
</div>
<div class="section" id="s-queries-over-related-objects">
<span id="queries-over-related-objects"></span><h3>Queries over related objects<a class="headerlink" href="#queries-over-related-objects" title="永久链接至标题">¶</a></h3>
<p>Queries involving related objects follow the same rules as queries involving
normal value fields. When specifying the value for a query to match, you may
use either an object instance itself, or the primary key value for the object.</p>
<p>For example, if you have a Blog object <code class="docutils literal notranslate"><span class="pre">b</span></code> with <code class="docutils literal notranslate"><span class="pre">id=5</span></code>, the following
three queries would be identical:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="p">)</span> <span class="c1"># Query using object instance</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="n">b</span><span class="o">.</span><span class="n">id</span><span class="p">)</span> <span class="c1"># Query using id from instance</span>
<span class="n">Entry</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">blog</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span> <span class="c1"># Query using id directly</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-falling-back-to-raw-sql">
<span id="falling-back-to-raw-sql"></span><h2>Falling back to raw SQL<a class="headerlink" href="#falling-back-to-raw-sql" title="永久链接至标题">¶</a></h2>
<p>If you find yourself needing to write an SQL query that is too complex for
Django's database-mapper to handle, you can fall back on writing SQL by hand.
Django has a couple of options for writing raw SQL queries; see
<a class="reference internal" href="sql.html"><span class="doc">Performing raw SQL queries</span></a>.</p>
<p>Finally, it's important to note that the Django database layer is merely an
interface to your database. You can access your database via other tools,
programming languages or database frameworks; there's nothing Django-specific
about your database.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Making queries</a><ul>
<li><a class="reference internal" href="#creating-objects">Creating objects</a></li>
<li><a class="reference internal" href="#saving-changes-to-objects">Saving changes to objects</a><ul>
<li><a class="reference internal" href="#saving-foreignkey-and-manytomanyfield-fields">Saving <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> and <code class="docutils literal notranslate"><span class="pre">ManyToManyField</span></code> fields</a></li>
</ul>
</li>
<li><a class="reference internal" href="#retrieving-objects">Retrieving objects</a><ul>
<li><a class="reference internal" href="#retrieving-all-objects">Retrieving all objects</a></li>
<li><a class="reference internal" href="#retrieving-specific-objects-with-filters">Retrieving specific objects with filters</a><ul>
<li><a class="reference internal" href="#chaining-filters">Chaining filters</a></li>
<li><a class="reference internal" href="#filtered-querysets-are-unique">Filtered <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are unique</a></li>
<li><a class="reference internal" href="#querysets-are-lazy"><code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are lazy</a></li>
</ul>
</li>
<li><a class="reference internal" href="#retrieving-a-single-object-with-get">Retrieving a single object with <code class="docutils literal notranslate"><span class="pre">get()</span></code></a></li>
<li><a class="reference internal" href="#other-queryset-methods">Other <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code> methods</a></li>
<li><a class="reference internal" href="#limiting-querysets">Limiting <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s</a></li>
<li><a class="reference internal" href="#field-lookups">Field lookups</a></li>
<li><a class="reference internal" href="#lookups-that-span-relationships">Lookups that span relationships</a><ul>
<li><a class="reference internal" href="#spanning-multi-valued-relationships">Spanning multi-valued relationships</a></li>
</ul>
</li>
<li><a class="reference internal" href="#filters-can-reference-fields-on-the-model">Filters can reference fields on the model</a></li>
<li><a class="reference internal" href="#expressions-can-reference-transforms">Expressions can reference transforms</a></li>
<li><a class="reference internal" href="#the-pk-lookup-shortcut">The <code class="docutils literal notranslate"><span class="pre">pk</span></code> lookup shortcut</a></li>
<li><a class="reference internal" href="#escaping-percent-signs-and-underscores-in-like-statements">Escaping percent signs and underscores in <code class="docutils literal notranslate"><span class="pre">LIKE</span></code> statements</a></li>
<li><a class="reference internal" href="#caching-and-querysets">Caching and <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s</a><ul>
<li><a class="reference internal" href="#when-querysets-are-not-cached">When <code class="docutils literal notranslate"><span class="pre">QuerySet</span></code>s are not cached</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#querying-jsonfield">Querying <code class="docutils literal notranslate"><span class="pre">JSONField</span></code></a><ul>
<li><a class="reference internal" href="#storing-and-querying-for-none">Storing and querying for <code class="docutils literal notranslate"><span class="pre">None</span></code></a></li>
<li><a class="reference internal" href="#key-index-and-path-transforms">Key, index, and path transforms</a></li>
<li><a class="reference internal" href="#containment-and-key-lookups">Containment and key lookups</a><ul>
<li><a class="reference internal" href="#contains"><code class="docutils literal notranslate"><span class="pre">contains</span></code></a></li>
<li><a class="reference internal" href="#contained-by"><code class="docutils literal notranslate"><span class="pre">contained_by</span></code></a></li>
<li><a class="reference internal" href="#has-key"><code class="docutils literal notranslate"><span class="pre">has_key</span></code></a></li>
<li><a class="reference internal" href="#has-keys"><code class="docutils literal notranslate"><span class="pre">has_keys</span></code></a></li>
<li><a class="reference internal" href="#has-any-keys"><code class="docutils literal notranslate"><span class="pre">has_any_keys</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#complex-lookups-with-q-objects">Complex lookups with <code class="docutils literal notranslate"><span class="pre">Q</span></code> objects</a></li>
<li><a class="reference internal" href="#comparing-objects">Comparing objects</a></li>
<li><a class="reference internal" href="#deleting-objects">Deleting objects</a></li>
<li><a class="reference internal" href="#copying-model-instances">Copying model instances</a></li>
<li><a class="reference internal" href="#updating-multiple-objects-at-once">Updating multiple objects at once</a></li>
<li><a class="reference internal" href="#related-objects">Related objects</a><ul>
<li><a class="reference internal" href="#one-to-many-relationships">One-to-many relationships</a><ul>
<li><a class="reference internal" href="#forward">Forward</a></li>
<li><a class="reference internal" href="#following-relationships-backward">Following relationships &quot;backward&quot;</a></li>
<li><a class="reference internal" href="#using-a-custom-reverse-manager">Using a custom reverse manager</a></li>
<li><a class="reference internal" href="#additional-methods-to-handle-related-objects">Additional methods to handle related objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#many-to-many-relationships">Many-to-many relationships</a></li>
<li><a class="reference internal" href="#one-to-one-relationships">One-to-one relationships</a></li>
<li><a class="reference internal" href="#how-are-the-backward-relationships-possible">How are the backward relationships possible?</a></li>
<li><a class="reference internal" href="#queries-over-related-objects">Queries over related objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#falling-back-to-raw-sql">Falling back to raw SQL</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="models.html"
                        title="上一章">Models</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="aggregation.html"
                        title="下一章">Aggregation</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/db/queries.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="models.html" title="Models">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="aggregation.html" title="Aggregation">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>